package com.yugao.fintech.antelope.infra.module.idgenerator;

import com.yugao.fintech.antelope.infra.InfraApi;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import com.yugao.fintech.framework.idgenerator.IdGeneratorHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * id生成器相关api

 */
@Slf4j
@Configuration
public class IdGenAutoConfig implements IdGeneratorHandler {
    @Autowired
    private InfraApi infraApi;

    private Short workId;

    @PostConstruct
    public void initWorkId() {
        if (Objects.nonNull(workId)) {
            log.warn("gen workId thread is started");
            return;
        }
        log.info("start gen id gen workId...");
        workId = infraApi.getIdGenNextWorkId();
        if (Objects.isNull(workId) || workId == -1) {
            throw new BizException("get next id gen workId fail");
        }
        log.info("end gen id gen workId, workId is [{}]", workId);

        log.info("start refresh id gen workId [{}] thread", workId);
        new Thread(() -> {
            while (true) {
                try {
                    infraApi.refreshIdGenWorkId(workId);
                    log.debug("start refresh id gen workId [{}]", workId);
                } finally {
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (Exception e) {
                        log.error("error: ", e);
                    }
                }
            }
        }).start();
    }

    @Override
    public short getWorkerId() {
        return workId;
    }
}
